package com.gg.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public abstract class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决POST请求中文乱码问题
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");//解决响应乱码
        String action = req.getParameter("action");

        /*if("login".equals(action)){
            login(req,resp);

        }else if ("regist".equals(action)){
            regist(req,resp);
        }*/

        //代码进一步优化，避免以后User模块添加新功能，如：修改密码，绑定手机号等业务功能时
        //还需要改动doPost追加大量else if，利用反射可以让开发者只专注于开发新功能方法代码
        try {
            //获取action业务 鉴别字符串，获取相应业务 方法反射对象
            Method method = this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
            //反射调用目标业务方法
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);//把异常抛给Filter过滤器
        }
    }
}
